package org.example.communication_room.Controller;

import jakarta.servlet.http.HttpSession;
import org.example.communication_room.dao.User;
import org.example.communication_room.service.impl.UserServiceImpl;
import org.example.communication_room.utils.ApiResponse;
import org.example.communication_room.utils.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

// 用户控制层
@RestController
@RequestMapping("/users")
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserServiceImpl userServiceImpl;
//    @Autowired
//    WebSocketRestController webSocketRestController;

    //    注册功能
    @CrossOrigin(origins = "*", maxAge = 3600)
    @PostMapping("/register")
    public ResponseEntity<ApiResponse<User>> registerUser(@RequestParam String username, @RequestParam String password) {

        User user = userServiceImpl.register(username, password);
        if (user != null) {
            logger.info("用户注册成功: {}", username);

            return ResponseEntity.ok(ApiResponse.success("用户注册成功.", user));
        } else {
            logger.warn("用户注册失败: {}", username);
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "用户注册失败."));
        }

    }

    //    登陆功能
    @CrossOrigin(origins = "*", maxAge = 3600)
    @PostMapping("/login")
    public ResponseEntity<ApiResponse<Map<String, String>>> loginUser(HttpSession session, @RequestParam String username, @RequestParam String password) {
        Map<String, String> tokens = userServiceImpl.login(username, password);
        if (tokens != null) {
            logger.info("用户登陆成功: {}", username);
            // 通知上线
//            webSocketRestController.notifyUser(username);
            return ResponseEntity.ok(ApiResponse.success("登陆成功.", tokens));
        } else {
            logger.warn("用户登陆失败: {}", username);
            return ResponseEntity.status(401).body(ApiResponse.error(401, "用户登陆失败"));
        }

    }

    //    刷新AcessToken
    @CrossOrigin(origins = "*", maxAge = 3600)
    @PostMapping("/refreshToken")
    public ResponseEntity<ApiResponse<String>> refreshToken(@RequestHeader("Authorization") String authorization) {
        System.out.println("token刷新");

        String refreshToken = authorization.substring("Bearer ".length());
        String newAccessToken = userServiceImpl.refreshAccessToken(refreshToken);
        if (newAccessToken != null) {
            logger.info("Token 刷新成功");
            return ResponseEntity.ok(ApiResponse.success("Token 刷新成功.", newAccessToken));
        } else {
            logger.warn("Token 刷新失败");
            return ResponseEntity.status(401).body(ApiResponse.error(401, "Token 刷新失败"));
        }

    }

    //    验证accessToken
    @CrossOrigin(origins = "*", maxAge = 3600)
    @GetMapping("/validateToken")
    public ResponseEntity<ApiResponse<Map<String, Object>>> validateToken(@RequestHeader("Authorization") String authorization) {
        String token = authorization.substring("Bearer ".length());
        logger.info(token);
        Map<String, Object> claims = JwtUtil.parseToken(token);
        if (claims != null) {
            logger.info("Token校验成功" + claims.get("userId"));
            return ResponseEntity.ok(ApiResponse.success("Token可用.", claims));
        } else {
            logger.warn("非法Token");
            return ResponseEntity.status(401).body(ApiResponse.error(401, "Invalid or expired token."));
        }
    }

    @CrossOrigin(origins = "*", maxAge = 3600)
    @GetMapping("/details")
    public ResponseEntity<ApiResponse<Map<String,String>>> getUserDetails(@RequestHeader("Authorization") String authorization) {

        String token = authorization.substring("Bearer ".length());
        logger.info(token);
        Map<String, Object> claims = JwtUtil.parseToken(token);
        String userId = String.valueOf(claims.get("userId")) ;
        logger.info("userId" + userId);
        User user = userServiceImpl.findUserById(String.valueOf(userId));

        if (user != null) {
            Map<String,String> userDetails = new HashMap<>();
            userDetails.put("id", String.valueOf(user.getUserId()));
            userDetails.put("username", user.getUsername());
            logger.info("用户详情获取成功: {}", userDetails);
            return ResponseEntity.ok(ApiResponse.success("用户详情获取成功.", userDetails));
        } else {
            logger.warn("找不到用户: {}", userId);
            return ResponseEntity.status(404).body(ApiResponse.error(404, "找不到用户"));
        }
    }

    //    用户下线
    @CrossOrigin(origins = "*", maxAge = 3600)
    @PostMapping("/logout")
    public ResponseEntity<ApiResponse<String>> logoutUser(@RequestHeader("Authorization") String authorization) {
        logger.info("用户下线");
//            获取id
        String token = authorization.substring("Bearer ".length());
        Map<String, Object> claims = JwtUtil.parseToken(token);
        logger.info("token" + token + "userId" + claims.get("userId"));
        String userId = String.valueOf(claims.get("userId"));
        userServiceImpl.logout(userId);
//        webSocketRestController.notifyUserOffline(userId);  // 通知WebSocket用户已下线
        return ResponseEntity.ok(ApiResponse.success("用户已注销成功."));
    }

//    @CrossOrigin(origins = "*", maxAge = 3600)
//    @GetMapping("/getOnlineCount")
//    public ResponseEntity<ApiResponse<Integer>> GetOnlineCount() {
//        Integer count = webSocketRestController.getOnlineCount();
//        return ResponseEntity.ok(ApiResponse.success(count));
//    }
}